<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{this.$router.currentRoute.name}}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <div v-if="seatsNumber!=null">
          <el-button size="small" type="info" plain v-if="seatsNumber.maxSeatsNumbers!=null">
            最大坐席数：{{seatsNumber.maxSeatsNumbers}}
          </el-button>
          <el-button size="small" type="info" plain v-if="seatsNumber.availableSeatsNum!=null">
            可用坐席数：{{seatsNumber.availableSeatsNum}}
          </el-button>
        <el-button size="small" type="info" plain v-if="seatsNumber.freeAvailableSeatsNum!=null">
          空余可用坐席数：{{seatsNumber.freeAvailableSeatsNum}}（账户的根部门管理员开启坐席时或分配给其它部门时都会减少这个数额）
        </el-button>
        <el-button size="small" type="success" v-if="seatsNumber.useSeatsNumbers!=null">
          已开启坐席数：{{seatsNumber.useSeatsNumbers}}
        </el-button>
      </div>
<!--      <el-page-header @back="goBack" :content="this.$router.currentRoute.name.substring(this.$router.currentRoute.name.indexOf('/')+1)">-->
<!--      </el-page-header>-->
    <!-- 系统通知列表卡片区 -->
      <el-form :inline="true" ref="form" :model="queryMap"  size="small" style="margin-top: 2vh">
        <el-row>
          <h4 style="margin: 1vh 0 2vh;color: #1f2d3d">条件查询区</h4>
        </el-row>
        <el-form-item>
          <el-select v-model="queryMap.accountName" style="width: 140px;" filterable placeholder="请选择账号" @change="searchSeatsAccountChange">

            <el-option
                v-for="(item,index) in accounts"
                :key="index"
                :label="item"
                :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryMap.userId" style="width: auto;" filterable placeholder="请选择用户">

            <el-option
                v-for="item in allSeats"
                :label="item.userName+'('+item.nickName+')'"
                :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item >
          <el-input
              style="width: 130px;"
              clearable
              v-model="queryMap.phone"
              placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
              clearable
              v-model="queryMap.status"
              style="width: 150px;"
              placeholder="请选择坐席状态"
          >

            <el-option label="未开启" value="0"></el-option>
            <el-option label="坐席开启" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
              clearable
              v-model="queryMap.isValidate"
              style="width: 170px;"
              placeholder="请选择号码验证状态"
          >

            <el-option label="未验证" value="0"></el-option>
            <el-option label="已验证" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
              clearable
              v-model="queryMap.isMove"
              style="width: 170px;"
              placeholder="请选择是否移动"
          >
            <el-option label="非移动" value="0"></el-option>
            <el-option label="移动号码" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item >
          <el-button  @click="reset" icon="el-icon-refresh">重置</el-button>
          <el-button type="primary" @click="searchSeatsNew" icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-form>
      <div style="margin-bottom: 10px;display: flex">
        <span class="hint" style="flex: 1;"></span>
        <el-button style="" icon="el-icon-phone-outline"  @click="opensSeatsStatus()"
                   :loading="btnLoading" :disabled="btnDisabled"
                   v-hasPermission="'users:editStatus'">批量开启外呼</el-button>
        <el-button style="" icon="el-icon-phone"  @click="closesSeatsStatus()"
                   :loading="btnLoading" :disabled="btnDisabled"
                   v-hasPermission="'users:editStatus'">批量关闭外呼</el-button>
      </div>

      <!-- 表格区域 -->
      <el-table ref="multipleTable" v-loading="" size="small" :data="seats" @selection-change="handleSelectionChange"
                border style="width: 100%;" height="420">
        <el-table-column type="selection" width="40"></el-table-column>
        <!-- <el-table-column type="selection" width="40"></el-table-column> -->
        <el-table-column prop="accountName" label="所属账户" width="150"></el-table-column>
        <el-table-column prop="nickName" label="用户昵称" width="150"></el-table-column>
        <el-table-column prop="userName" label="用户名" width="150"></el-table-column>
        <el-table-column prop="telNumber" label="话机号码" width="150"></el-table-column>
        <el-table-column label="坐席状态" width="150">
          <template v-slot="scope">{{getStatus(scope.row.status)}}</template>
        </el-table-column>
        <el-table-column label="是否移动" width="150">
          <template v-slot="scope">{{getIsMove(scope.row.isMove)}}</template>
        </el-table-column>
        <el-table-column label="号码验证状态" width="150">
          <template v-slot="scope">{{getIsValidate(scope.row.isValidate)}}</template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="150"></el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <!--          该部分需要权限控制，仅超级管理员与部门管理员-->
          <template fixed="right" v-slot="scope">
            <el-button
                size="small"
                type="success"
                round icon="el-icon-phone-outline"
                v-if="scope.row.status==0"
                @click="changeSeatStatus(scope.row.userId, scope.row.status,scope.row.accountName)"
                v-hasPermission="'users:editStatus'"
            >
              开启外呼
            </el-button>
            <el-button
                size="small"
                type="info"
                round icon="el-icon-phone"
                v-else-if="scope.row.status==1"
                v-hasPermission="'users:editStatus'"
                @click="changeSeatStatus(scope.row.userId, scope.row.status)"
            >
              关闭外呼
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          style="margin-top:10px;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryMap.pageNum"
          :page-sizes="this.$globalVar.sizes"
          :page-size="queryMap.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
    </el-card>

  </div>
</template>
<script>
export default {
  data() {
    return {
      btnLoading: false,
      btnDisabled: false,
      loading: true,
      total: 0,
      multipleSelection:[],
      accounts:[],
      seats: [],
      allSeats:[],
      seatsNumber:null,
      //查询对象
      queryMap: {
        pageNum: 1,
        pageSize: 10,
        nickName: '',
        userName: '',
        phone: '',
        status:'',
        isValidate:'',
        isMove:'',
        accountName:'',
        userId:null
      },
      statusMap:{
        0:'未开启',
        1:'已开启',
      },
      isMoveMap:{
        0:'否',
        1:'是',
      },
      isValidateMap:{
        0:'未验证',
        1:'已验证',
      }
    };
  },
  async created(){
    await this.searchSeats();
    await this.getAllAccountList();
  },
  methods: {
    //获取分区制状态
    async getZoningStatus(accountName){
      const {data: res} = await this.$http.get("system/zoning/getZoningStatus",{params:{accountName:accountName}});
      if (res.success) {
        return res.data;
      } else {
        console.log("获取分区制状态失败:" + res.data.errorMsg);
        return 0;
      }
    },
    getStatus(status) {
      return this.statusMap[status] || '已冻结';
    },
    getIsMove(isMove) {
      return this.isMoveMap[isMove] || '状态错误';
    },
    getIsValidate(isValidate) {
      return this.isValidateMap[isValidate] || '状态错误';
    },
    /**
     * 重置
     */
    reset(){
      this.queryMap= {
        pageNum: 1,
        pageSize: 10,
        nickName: '',
        userName: '',
        phone: null,
        status:null,
        isValidate:null,
        isMove:null,
        accountName:'',
        userId:null
      };
      this.seatsNumber=null;
      this.searchSeats();
    },
    async searchSeatsAccountChange(){
      this.queryMap.userId = null;
      this.searchSeats();
    },
    /**
     * 全选功能
     *
     */
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /**
     *  改变页码
     */
    handleSizeChange(newSize) {
      this.queryMap.pageSize = newSize;
      this.searchSeats();
    },
    /**
     * 翻页
     */
    handleCurrentChange(current) {
      this.queryMap.pageNum = current;
      this.searchSeats();
    },
    /**
     * 查询
     */
    async searchSeats(){
      const {data:res}=await this.$http.get("comcentre/seats/findList",{
        params:this.queryMap
      });
      if(!res.success){
        console.log(res)
        return this.$message.error("获取坐席列表失败:"+res.data.errorMsg);
      }else {
        this.searchAllSeats();
        this.seats = res.data.rows;
        this.total = res.data.total;
        this.getSeatsNumber();
        this.loading=false
      }
    },
    /**
     * 得到一定条件下的所有坐席
     */
    async searchAllSeats(){
      const {data:res}=await this.$http.get("comcentre/seats/getAllSeats",{
        params:this.queryMap
      });
      if(!res.success){
        return this.$message.error("获取坐席列表失败:"+res.data.errorMsg);
      } else {
        this.allSeats = res.data;
        this.loading=false
      }
    },
    /**
     * 单击设置状态
     */
    async changeSeatStatus(userId, status ,accountName){
      this.btnLoading = true;
      this.btnDisabled = true;
      // 反转 开启|未开启 状态
      if (status==0){
        status=1
      }else if(status==1){
        status=0
      }else {
        return this.$message.error("该用户状态非正常，无法设置外呼");
      }
      let isZoning=await this.getZoningStatus(accountName);
      //判断是否开启了分区制
      if(isZoning==0){
        const {data:res}=await this.$http.put("comcentre/seats/setSeatStatus",{
          userId:userId,status:status
        });
        if(!res.success){
          this.btnLoading = false;
          this.btnDisabled = false;
          return this.$message.error("外呼开启失败:"+res.data.errorMsg);
        }
      }else if(isZoning==1){
        const {data:res}=await this.$http.put("system/zoning/setZoningSeatStatus",{
          userId:userId,status:status
        });
        if(!res.success){
          this.btnLoading = false;
          this.btnDisabled = false;
          return this.$message.error("外呼开启失败:"+res.data.errorMsg);
        }
      }
      this.searchSeats()
      this.getSeatsNumber();
      this.btnLoading = false;
      this.btnDisabled = false;
      this.$message.success("设置成功")
    },
    /**
     * 多选设置关闭坐席状态
     */
    closesSeatsStatus(){
      this.btnLoading = true;
      this.btnDisabled = true;
      if (this.multipleSelection.length===0){
        this.btnLoading = false;
        this.btnDisabled = false;
        return this.$message.info("未选中");
      }
      this.$confirm('确认给选中用户关闭坐席吗','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        for (let seat of this.multipleSelection) {
          let isZoning=await this.getZoningStatus(seat.accountName);
          if (seat.status == 0 || seat.status!=1) {
            continue;
          }
          if(isZoning==0){
            const {data: res} = await this.$http.put("comcentre/seats/setSeatStatus", {
              userId: seat.userId, status: 0
            });
            if (!res.success) {
              this.btnLoading = false;
              this.btnDisabled = false;
              return this.$message.error("外呼关闭失败:" + res.data.errorMsg);
            }
          }else if (isZoning==1){
            const {data: res} = await this.$http.put("system/zoning/setZoningSeatStatus", {
              userId: seat.userId, status: 0
            });
            if (!res.success) {
              this.btnLoading = false;
              this.btnDisabled = false;
              return this.$message.error("外呼关闭失败:" + res.data.errorMsg);
            }
          }
          this.searchSeats()
          this.getSeatsNumber();
        }
        this.btnLoading = false;
        this.btnDisabled = false;
        this.$message.success("设置成功");
      }).catch(()=>{
        this.btnLoading = false;
        this.btnDisabled = false;
        this.$message.info('已取消')
      })

    },
    /**
     * 多选设置开启坐席状态
     */
    opensSeatsStatus(){
      this.btnLoading = true;
      this.btnDisabled = true;
      if (this.multipleSelection.length===0){
        this.btnLoading = false;
        this.btnDisabled = false;
        return this.$message.info("未选中");
      }
      this.$confirm('确认给选中用户开启坐席吗','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        for (let seat of this.multipleSelection) {
          if (seat.status == 1 || seat.status!=0) {
            continue;
          }
          let isZoning=await this.getZoningStatus(seat.accountName);
          if(isZoning==0){
            const {data: res} = await this.$http.put("comcentre/seats/setSeatStatus", {
              userId: seat.userId, status: 1
            });
            if (!res.success) {
              this.btnLoading = false;
              this.btnDisabled = false;
              return this.$message.error("外呼开启失败:" + res.data.errorMsg);
            }
          }else if (isZoning==1){
            const {data: res} = await this.$http.put("system/zoning/setZoningSeatStatus", {
              userId: seat.userId, status: 1
            });
            if (!res.success) {
              this.btnLoading = false;
              this.btnDisabled = false;
              return this.$message.error("外呼开启失败:" + res.data.errorMsg);
            }
          }
          this.searchSeats()
          this.getSeatsNumber();
        }
        this.btnLoading = false;
        this.btnDisabled = false;
        this.$message.success("设置成功");
      }).catch(()=>{
        this.btnLoading = false;
        this.btnDisabled = false;
        this.$message.info('已取消')
      })
    },
    /**
     * 查询所有账号
     */
    async getAllAccountList(){
      const {data: res} = await this.$http.get("/system/user/qt/findRoleList");
      if(!res.success){
        return this.$message.error("获取账号列表失败:"+res.data);
      }
      if (res.data!=null){
        this.accounts = res.data;
      }else{
        this.accounts=null
      }
    },
    /**
     * 得到当前坐席的最大数量与已使用数量
     */
    async getSeatsNumber(){
      if (this.queryMap.accountName==null||this.queryMap.accountName==''){
        return;
      }
      let isZoning=await this.getZoningStatus(this.queryMap.accountName);
      if (isZoning==0){
        const {data: res} = await this.$http.get("comcentre/seats/getSeatsNumber",{
          params:this.queryMap
        });
        if(!res.success){
          console.log(res)
          return this.$message.error("获取可操作坐席数量失败:"+res.data);
        }
        this.seatsNumber=res.data;
      }else if (isZoning==1){
        const {data: res} = await this.$http.get("system/zoning/getZoningSeatsNumber",{
          params:this.queryMap
        });
        if(!res.success){
          console.log(res)
          return this.$message.error("获取可操作坐席数量失败:"+res.data);
        }
        this.seatsNumber=res.data;
      }
    },
    searchSeatsNew(){
      this.queryMap.pageNum=1;
      this.searchSeats();
    }
  },

};
</script>

<style scoped>

</style>
